package com.belizer.pay.service.impl;

import com.alipay.easysdk.base.oauth.models.AlipaySystemOauthTokenResponse;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.app.models.AlipayTradeAppPayResponse;
import com.alipay.easysdk.payment.common.models.AlipayTradeRefundResponse;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.alipay.easysdk.util.generic.models.AlipayOpenApiGenericResponse;
import com.aliyun.tea.utils.StringUtils;
import com.belizer.pay.service.AliPayService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class AliPayServiceImpl implements AliPayService {

    public String createFaceToFacePaymentQrCode(String subject, String orderNo, BigDecimal amount) {
        try {
            AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace().preCreate(subject,orderNo,amount.toString());

            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                System.out.println("面对面扫码支付调用成功");
                return response.getQrCode();
            } else {
                System.err.println("面对面扫码支付调用失败，原因：" + response.msg + "，" + response.subMsg);
                throw new RuntimeException(response.getMsg());
            }
        }catch (Exception e) {
            System.err.println("面对面扫码支付调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    @Override
    public String appPay(String subject, String orderNo, BigDecimal amount, String notifyUrl) {
        try {
            AlipayTradeAppPayResponse response
                    = Factory.Payment.App().pay(subject, orderNo, amount.toString());
            System.out.println("app支付调用成功");
            return response.getBody();
        }catch (Exception e) {
            System.err.println("app支付调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }

    }

    public boolean refund(String orderNo,BigDecimal refundAmount) {
        try {
            AlipayTradeRefundResponse response = Factory.Payment.Common().refund(orderNo, refundAmount.toString());

            if (ResponseChecker.success(response)) {
                //退款调用成功
                System.out.println("退款调用成功");
                return true;
            }else {
                //退款调用失败
                System.err.println("退款调用失败，原因：" + response.msg + "，" + response.subMsg);
                throw new RuntimeException(response.getMsg() + "，" + response.getSubMsg());
            }

        }catch (Exception e) {
            System.err.println("退款调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
    }


    public boolean withdraw(String withdrawNo,String aliPayAccount,String name,String aliPayUserId,BigDecimal amount) {
        try {
            Map<String,Object> bizParams = new HashMap<>();
            bizParams.put("out_biz_no",withdrawNo);
            bizParams.put("trans_amount",amount.toString());
            bizParams.put("biz_scene","DIRECT_TRANSFER");
            bizParams.put("product_code","TRANS_ACCOUNT_NO_PWD");
            bizParams.put("order_title","服务费");

            Map<String,String> payeeInfo = new HashMap<>();
            if (!StringUtils.isEmpty(aliPayUserId)) {
                payeeInfo.put("identity_type","ALIPAY_USER_ID");
                payeeInfo.put("identity",aliPayUserId);
            }else if (!StringUtils.isEmpty(aliPayAccount)) {
                payeeInfo.put("identity_type","ALIPAY_LOGON_ID");
                payeeInfo.put("identity",aliPayAccount);
                payeeInfo.put("name",name);
            }
            bizParams.put("payee_info",payeeInfo);
            AlipayOpenApiGenericResponse response = Factory.Util.Generic().execute(
                    "alipay.fund.trans.uni.transfer",
                    null,
                    bizParams
            );

            if (ResponseChecker.success(response)) {
                System.out.println("支付宝单笔转账接口调用成功");
                return true;
            }else {
                System.err.println("支付宝单笔转账接口调用失败，原因：" + response.msg + "，" + response.subMsg);
                throw new RuntimeException(response.getMsg() + "，" + response.getSubMsg());
            }
        }catch (Exception e) {
            System.err.println("支付宝单笔转账接口调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public Map<String,String> authToken(String authCode) {
        try {
            AlipaySystemOauthTokenResponse response = Factory.Base.OAuth().getToken(authCode);

            if (ResponseChecker.success(response)) {
                String userId = response.getUserId();
                String accessToken = response.getAccessToken();

                Map<String,String> authTokenRes = new HashMap<>();
                authTokenRes.put("aliPayUserId",userId);
                authTokenRes.put("aliPayAccessToken",accessToken);

                return authTokenRes;
            } else  {
                System.err.println("支付宝换取授权访问令牌接口调用失败，原因：" + response.msg + "，" + response.subMsg);
                throw new RuntimeException(response.getMsg() + "，" + response.getSubMsg());
            }
        }catch (Exception e) {
            System.err.println("支付宝换取授权访问令牌接口调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public Map<String, String> geyAliPayUserInfo(String accessToken) {
        try {
            Map<String,String> textParams = new HashMap<>();
            textParams.put("auth_token",accessToken);
//            bizParams.put("","");
//            bizParams.put("","");
//            bizParams.put("","");

            AlipayOpenApiGenericResponse response = Factory.Util.Generic().execute(
                    "alipay.user.info.share",
                    textParams,
                    null
            );

            if (ResponseChecker.success(response)) {
                String httpBody = response.getHttpBody();
                ObjectMapper objectMapper = new ObjectMapper();
                return objectMapper.readValue(httpBody, new TypeReference<Map<String,String>>() {});
            }else {
                System.err.println("支付宝会员授权信息查询接口调用失败，原因：" + response.msg + "，" + response.subMsg);
                throw new RuntimeException(response.getMsg() + "，" + response.getSubMsg());
            }
        }catch (Exception e) {
            System.err.println("支付宝会员授权信息查询接口调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
    }




}
